package cn.itcast.service.impl;

import cn.itcast.dao.RoleDao;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.pojo.Role;
import cn.itcast.service.RoleService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult findRoleByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> page = roleDao.findRoleByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public boolean deleteRoleById(Integer id) {
        //判断关系表中是否存在相关数据，没有数据才能进行删除
        if (roleDao.findMenuIdByRoleId(id).length==0&&roleDao.findPermissionIdByRoleId(id).length==0) {
            return roleDao.deleteRoleById(id)>0;
        }
        return false;
    }

    @Override
    public Role findRoleById(Integer id) {
        return roleDao.findRoleById(id);
    }

    @Override
    public Integer[] findMenuIdByRoleId(Integer id) {
        return roleDao.findMenuIdByRoleId(id);
    }

    @Override
    public Integer[] findPermissionIdByRoleId(Integer id) {
        return roleDao.findPermissionIdByRoleId(id);
    }

    @Override
    public void addRole(Role role, Integer[] permissionIds, Integer[] menuIds) {
        //添加角色需要向三张表中进行添加
        //添加到角色表
        roleDao.addRole(role);
        //添加到角色菜单表
        if (menuIds==null||menuIds.length==0){
            return;
        }
        for (Integer menuId : menuIds) {
            roleDao.addRoleAndMenu(role.getId(),menuId);
        }
        //添加到角色权限表
        if (permissionIds==null||permissionIds.length==0){
            return;
        }
        for (Integer permissionId : permissionIds) {
            roleDao.addRoleAndPermission(role.getId(),permissionId);
        }
    }

    @Override
    public void updateRole(Role role, Integer[] permissionIds, Integer[] menuIds) {
        //对三张表进行修改
        //修改角色表
        roleDao.updateRole(role);
        //修改角色菜单表  先删除  再添加
        roleDao.deleteRoleMenu(role.getId());
        if (menuIds==null||menuIds.length==0){
            return;
        }
        for (Integer menuId : menuIds) {
            roleDao.addRoleAndMenu(role.getId(),menuId);
        }
        //修改角色权限表  先删除  再添加
        roleDao.deleteRolePermission(role.getId());
        if (permissionIds==null||permissionIds.length==0){
            return;
        }
        for (Integer permissionId : permissionIds) {
            roleDao.addRoleAndPermission(role.getId(),permissionId);
        }

    }

    @Override
    public List<Role> findAllRole() {
        return roleDao.findRoleByCondition(null).getResult();
    }
}
